package com.lz.service.impl;

import com.lly835.bestpay.enums.BestPayTypeEnum;
import com.lly835.bestpay.model.PayRequest;
import com.lly835.bestpay.model.PayResponse;
import com.lly835.bestpay.model.RefundRequest;
import com.lly835.bestpay.model.RefundResponse;
import com.lly835.bestpay.service.impl.BestPayServiceImpl;
import com.lz.entity.OrderMasterQuery;
import com.lz.enums.ResultEnum;
import com.lz.exception.SellException;
import com.lz.service.OrderService;
import com.lz.service.PayService;
import com.lz.utils.JsonUtil;
import com.lz.utils.MathUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * 支付业务实现
 * Created by Administrator on 2018/8/29 0029.
 */
@Service
@Slf4j
public class PayServiceImpl implements PayService {

    private static final String ORDER_NAME = "微信点餐订单";

    @Autowired
    private BestPayServiceImpl bestPayService;

    @Autowired
    private OrderService orderService;

    /**
     * 发起支付，返回预支付
     * @param orderMasterQuery
     * @return
     */
    public PayResponse create(OrderMasterQuery orderMasterQuery) {
        PayRequest payRequest = new PayRequest();
        payRequest.setOpenid(orderMasterQuery.getBuyerOpenid());
        payRequest.setOrderAmount(orderMasterQuery.getOrderAmount().doubleValue());
        payRequest.setOrderId(orderMasterQuery.getOrderId());
        payRequest.setOrderName(ORDER_NAME);
        payRequest.setPayTypeEnum(BestPayTypeEnum.WXPAY_H5);
        log.info("【微信支付】发起支付，request={}", JsonUtil.toJson(payRequest));

        PayResponse payResponse = bestPayService.pay(payRequest);
        log.info("【微信支付】发起支付，response={}",JsonUtil.toJson(payResponse));

        return payResponse;
    }

    /**
     * 支付
     * @param notifyData
     * @return
     */
    @Override
    public PayResponse notify(String notifyData) {
        //1.验证签名
        //2.支付状态
        //3.支付金额
        //4.支付人（下单人 和 支付人，根据业务）
        PayResponse payResponse = bestPayService.asyncNotify(notifyData);
        log.info("【微信支付】异步通知，payResponse={}",JsonUtil.toJson(payResponse));
        //查询订单，判断订单支付存在
        OrderMasterQuery orderMasterQuery = orderService.findOne(payResponse.getOrderId());
        if (orderMasterQuery == null){
            log.error("【微信支付】异步通知，订单不存在,orderId={}",payResponse.getOrderId());
            throw new SellException(ResultEnum.ORDER_NOT_EXIST);
        }
        //判断金额是否一直(decimal精度)
        if (!MathUtil.equ(payResponse.getOrderAmount(),orderMasterQuery.getOrderAmount().doubleValue())){
            log.error("【微信支付】异步通知，订单金额不一致，orderId={},微信金额={},系统金额={}",
                    payResponse.getOrderId(),
                    payResponse.getOrderAmount(),
                    orderMasterQuery.getOrderAmount());
            throw new SellException(ResultEnum.WXPAY_NOTIFY_MONEY_VERIFY_ERROR);
        }
        //修改订单状态
        orderService.paidOrder(orderMasterQuery);

        return payResponse;
    }

    /**
     * 退款
     * @param orderMasterQuery
     */
    @Override
    public RefundResponse refund(OrderMasterQuery orderMasterQuery) {
        RefundRequest refundRequest = new RefundRequest();
        refundRequest.setOrderId(orderMasterQuery.getOrderId());
        refundRequest.setPayTypeEnum(BestPayTypeEnum.WXPAY_H5);
        refundRequest.setOrderAmount(orderMasterQuery.getOrderAmount().doubleValue());
        log.info("【微信支付】request={}",refundRequest);
        RefundResponse refund = bestPayService.refund(refundRequest);
        log.info("【微信支付】response={}",refund);
        return refund;
    }
}
